#!/bin/bash

source /etc/profile

# config Docker
if [ ! -e "/etc/docker/daemon.json" ]; then
	# 1. change docker's mirror to ustc's mirror
	if [ ! -d "/etc/docker" ]; then
		sudo mkdir /etc/docker
	fi
	echo "{
	\"registry-mirrors\": [\"https://docker.mirrors.ustc.edu.cn\"]
}" | sudo tee -a /etc/docker/daemon.json
	# 2. restart service
	sudo systemctl daemon-reload
	sudo systemctl restart docker
fi

# install Docker-compose
# 1. install pip & change pip source
sudo apt-get -y install python3-pip
if [ $? -ne 0 ]; then
	echo "install python3-pip error"
	exit -1
fi

if [ ! -d "$HOME/.pip" ]; then
	mkdir $HOME/.pip
fi
if [ ! -e "$HOME/.pip/pip.conf" ]; then
echo "[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com" > $HOME/.pip/pip.conf
fi

# 2. install docker-compose
sudo apt-get -y install docker-compose
if [ $? -ne 0 ]; then
	echo "docker-compose install error"
	exit -1
fi
# 3. watch docker-compose version
# docker-compose -version

# install fabric
# 1. clone source code from github and install
if [ ! -d "$HOME/go/src/github.com/hyperledger/" ]; then
	mkdir -p $HOME/go/src/github.com/hyperledger/
fi
cd $HOME/go/src/github.com/hyperledger/
if [ ! -d "fabric" ]; then
	git clone -q "https://gitee.com/czy233/fabric.git"
	if [ $? -ne 0 ]; then
		echo "clone fabric code error"
		exit -1
	fi
	cd ./fabric
	git checkout v1.4
else
	cd ./fabric
	git pull
	git checkout v1.4
fi

# cd $HOME/go/src/github.com/hyperledger/fabric/scripts/
# ./bootstrap.sh
# if [ $? -ne 0 ]; then
# 	echo "fabric bootstrap error"
# 	exit -1
# fi
# 2. build fabric command
cd $HOME/go/src/github.com/hyperledger/fabric/
make release
# 3. config env PATH
echo "export PATH=$GOPATH/src/github.com/hyperledger/fabric/release/linux-amd64/bin:$PATH" | sudo tee -a /etc/profile
source /etc/profile
# # 4. start fabric network
# cd $GOPATH/src/fabric/scripts/fabric-samples/test-network
# # ./network.sh -h  # help
# ./network.sh up
# if [ $? -ne 0 ]; then
# 	echo "fabric network up error"
# 	exit -1
# fi
# ./network.sh down
# echo "finish install fabric"

# ./network.sh createChannel
# cp $HOME/ceph_fabric_config/smartcontract.go $HOME/go/src/fabric/scripts/fabric-samples/asset-transfer-basic/chaincode-go/chaincode/smartcontract.go
# ./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go